#!/bin/bash

PROJECT="club"
DST_SERVER="0.0.0.1 0.0.0.2 0.0.0.3"
#本机IP
SRC_SERVER="0.0.0.0"
DST_PORT="8071"
DEPLOY_PATH="/data/web/hf_app/build.club/ROOT/"
TARGET_CONFIG_PATH="/data/web/hf_app/build.club/ROOT/WEB-INF/classes/"
SOURCE_CONFIG_PATH="hefan/build.club/sync/config-toolkit.properties"
RSYNC_PATH="hefan/build.club/ROOT/"
TOMCAT="/usr/local/app/tomcat/"
RETURN_CODE="200"
PORT="1922"

### sync file to server
### $1 for dst server ip addr
sync(){
	ssh -t -p $PORT $1 "rsync -avP --delete $SRC_SERVER::$RSYNC_PATH $DEPLOY_PATH; \
		rsync -avP --delete $SRC_SERVER::$SOURCE_CONFIG_PATH $TARGET_CONFIG_PATH"
}

### restart tomcat
### $1 for dst server ip addr
restart(){
	ssh -t -p $PORT $1 "ps aux |grep -v grep |grep $TOMCAT|awk '{print \$2}'|xargs kill -9 "
	ssh -p $PORT $1 "source /etc/profile ; $TOMCAT/bin/startup.sh"
}

### success check
check(){
        STATUS=1
        for i in `seq 1 60`;do
                code=`curl -I http://$1:$DST_PORT/index.jsp --connect-timeout 2|grep HTTP|awk '{print $2}' 2>/dev/null`
                if [ $code -eq $RETURN_CODE ];then
                        STATUS=0
                        break
                else
			echo "$1 tomcat has not started , please wait............"
                        sleep 1
                fi
        done
}

check_compile_status(){
	if [ "`ls -A $DEPLOY_PATH`" = "" ]; then
		echo "$DEPLOY_PATH is indeed empty"
		exit 1
	else
		echo "$DEPLOY_PATH is not empty, go on..."
	fi
}

### script start


for IP in $DST_SERVER;do
	check_compile_status
        sync $IP
        restart $IP
        check $IP
        if [ $STATUS -eq 0 ];then
        	echo "$IP $PROJECT gkd_application started....."
	else
                echo "fuck u"
        fi
done
